import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import "./index.scss";
import { useClickAway } from "ahooks";
import axios from "axios";
function XtxCity({
  fullLocation,
  change,
}: {
  fullLocation: string;
  change: (vlaue: any) => void;
}) {
  const target = useRef<HTMLDivElement>(null);
  const [show, setShow] = useState(false);
  const [list, setList] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [ProvinceData, setProvinceData] = useState<{
    provincecode: string;
    provincename: string;
    citycode: string;
    cityname: string;
    countrycode: string;
    countryname: string;
    fullLocation: string;
  }>();
  // useClickAway(() => close(), target.current);
  const getCityData = () => {
    // 这个位置可能有异常操作，封装成promise
    return new Promise((resolve, reject) => {
      if ((window as any).cityData) {
        // 有缓存
        resolve((window as any).cityData);
      } else {
        // 无缓存
        const url =
          "https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json";
        axios.get(url).then((res) => {
          (window as any).cityData = res.data;
          resolve((window as any).cityData);
        });
      }
    });
  };

  const open = () => {
    setLoading(true);
    setProvinceData({
      provincecode: "",
      provincename: "",
      citycode: "",
      cityname: "",
      countrycode: "",
      countryname: "",
      fullLocation: "",
    });
    setShow(true);

    async function cityList() {
      const res: any = await getCityData();
      setList(res);
      setLoading(false);
    }
    cityList();
  };
  const close = () => {
    setShow(false);
  };
  const toggle = function () {
    show ? close() : open();
  };

  const cityClick = function (i: any) {
    if (i.level === 0) {
      setProvinceData((pre: any) => ({
        ...pre,
        provincecode: i.code,
        provincename: i.name,
      }));
    } else if (i.level === 1) {
      setProvinceData((pre: any) => ({
        ...pre,
        citycode: i.code,
        cityname: i.name,
      }));
    } else {
      setProvinceData((pre: any) => {
        return {
          ...pre,
          countrycode: i.code,
          countryname: i.name,
          fullLocation: `${pre.provincename}  ${pre.cityname}  ${i.name}`,
        };
      });
      close();
    }
  };
  useEffect(() => {
    if (ProvinceData?.countrycode) {
      change(ProvinceData);
    }
  }, [ProvinceData]);
  const currentList: any = useMemo(() => {
    let obj: any = list;
    if (ProvinceData?.provincecode && ProvinceData.provincename) {
      obj = list.find(
        (item: any) => item.code === ProvinceData.provincecode
      ).areaList;
    }
    if (ProvinceData?.citycode && ProvinceData.cityname) {
      obj = obj.find(
        (item: any) => item.code === ProvinceData.citycode
      ).areaList;
    }
    return obj;
  }, [ProvinceData, list]);

  return (
    <>
      <div className="xtx-city" ref={target}>
        <div className="select" onClick={toggle}>
          {fullLocation ? (
            <span className="value">{fullLocation}</span>
          ) : (
            <span className="placeholder">请选择配送地址</span>
          )}
          <i className="iconfont icon-angle-down"></i>
        </div>
        {show && (
          <div className="option">
            {loading ? (
              <div className="loading"></div>
            ) : (
              currentList?.map((item: any) => (
                <span
                  key={item.code}
                  className="ellipsis"
                  onClick={() => cityClick(item)}
                >
                  {item.name}
                </span>
              ))
            )}
          </div>
        )}
      </div>
    </>
  );
}
export default XtxCity;
